package com.pederszt.foodiary.dao;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import com.pederszt.foodiary.jdo.Item;

public class ItemDAOImpl
{
	public void saveItem(Item item)
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		tx = pm.currentTransaction();
		try
		{
			// Start the transaction
			tx.begin();

			// Persist it to the datastore
			pm.makePersistent(item);

			// Commit the transaction, flushing the object to the datastore
			tx.commit();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (tx.isActive())
			{
				// Error occurred so rollback the transaction
				tx.rollback();
			}
			pm.close();
		}
	}

	public List<Item> getItemList(String search)
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Item.class);
		List<Item> items = (List<Item>) q.execute(search);
		List<Item> result = new ArrayList<Item>();

		for (Item item : items)
		{
			if (item.getSearchValue().toUpperCase().contains(search.toUpperCase()))
			{
				result.add(item);
			}
		}

		return result;
	}
}
